import { useState, useEffect, useContext } from 'react';
import { NavBar, Popup, SearchBar, Tabs, List, Image, Button, InfiniteScroll, Checkbox } from 'antd-mobile';
import AvatarImage from '../AvatarImage';

import { MySdkStoreContext } from '../../context';

import './style.scss';

export default function(props) {
  const mySdkStore = useContext(MySdkStoreContext);
  const { onOk, onClose, listFilterFunc } = props;
  const [isMultiSelecting, setIsMultiSelecting] = useState(false);
  const [list, setList] = useState([]);
  // 已选中的单聊会话
  const [selectedSingle, setSelectedSingle] = useState([]);
  // 已选中的群聊会话
  const [selectedGroup, setSelectedGroup] = useState([]);
  const [tabKey, setTabKey] = useState('single');
  const [pagination, setPagination] = useState({ pageIndex: 1, totalPage: 1 });

  // 获取列表数据
  const getList = async (pageIndex, type = tabKey) => {
    // todo: 缺少totalpage，或totalItemCount
    const res =  await mySdkStore.sdk.queryConversationList({ pageIndex, type, pageSize: 20 });
    let { list: rows, totalPage, currentPageIndex } = res;
    if (typeof listFilterFunc === 'function') {
      rows = listFilterFunc(rows);
    }
    setPagination({ pageIndex: currentPageIndex, totalPage });
    setList(list => pageIndex === 1 ? rows : [...list, ...rows]);
  }

  const getNextData = async () => {
    await getList(pagination.pageIndex + 1);
  }

  const handleChange = (key) => {
    setTabKey(key);
    getList(1, key);
  }

  useEffect(() => {
    getList(1);
  }, []);

  // 多选模式下点击”确定“按钮事件或单选模式下点击单条会话，调用props onOk回调
  const handleOk = (cid?: string) => {
    if (cid) {
      // 处理单选的情况，直接转发至该回话
      if (isMultiSelecting) {
        return;
      }

      onOk([{ cid }]);
      return;
    }

    // 处理多选模式的情况，合并”单聊“和”群聊“的会话
    onOk([...selectedSingle, ...selectedGroup].map(cid => ({ cid })));
  }

  // 渲染列表数据
  const renderList = () => {
    return <><List style={{ '--border-inner': 0 }}>
      {list.map(item => {
        return <List.Item
          key={item.cid}
          prefix={
          <>
            { isMultiSelecting && <Checkbox value={item.cid} style={{ marginRight: 12, marginBottom: 10 }} /> }
            <AvatarImage
              src={item.sessionLogoUrl}
              style={{ display: 'inline-block', borderRadius: 8 }}
              fit='cover'
              width={36}
              height={36}
              groupName={item.name}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
            />
        </>}><div onClick={() => handleOk(item.cid)}>{item.type === 'group' ? item.name : (item.nickName || item.singleSubUser.userId)}</div></List.Item>
      })}
    </List>
    <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
  </>
  }

  return <Popup
    visible={true}
    bodyClassName="popupbody">
      <div className="selectContractorComponent">
        <NavBar
          onBack={() => onClose()} style={{ background: '#fff', border: 'none' }}
          right={
            isMultiSelecting ?
              <a onClick={() => { setIsMultiSelecting(false) }} style={{ color: 'rgba(0,0,0,0.65)' }}>取消多选</a> :
              <a onClick={() => { setIsMultiSelecting(true) }} style={{ color: 'rgba(0,0,0,0.65)' }}>多选</a>
          }>
          选择联系人
        </NavBar>
        {/* todo: queryConversationList 没有关键词搜索参数 */}
        {/* <SearchBar className="searchBar" /> */}
        <Tabs onChange={handleChange} className="pageTab">
          <Tabs.Tab title='转发到个人' key='single'>
            <Checkbox.Group onChange={(val) => setSelectedSingle(val)}>
              {renderList()}
            </Checkbox.Group>
          </Tabs.Tab>
          <Tabs.Tab title='转发到群' key='group'>
            <Checkbox.Group onChange={(val) => setSelectedGroup(val)}>
              {renderList()}
            </Checkbox.Group>
          </Tabs.Tab>
        </Tabs>
        { isMultiSelecting &&
          <div className="bottomOperationBar">
            <div style={{ lineHeight: '29px' }}>已选择：{selectedSingle.length}人，{selectedGroup.length}个群</div>
            <Button color="primary" size="small" onClick={() => handleOk()} disabled={!selectedGroup.length && !selectedSingle.length }>确定</Button>
          </div> }
      </div>
  </Popup>;
}